package org.csu.mybigpro.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.csu.mybigpro.DTO.GradingReportDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class AssessmentService {

    @Autowired
    private WordParserService wordParserService;

    @Autowired
    private AiService aiService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public GradingReportDto gradeAndAnalyze(MultipartFile examFile, MultipartFile answersFile) throws Exception {
        String examText = wordParserService.extractText(examFile);
        String answersText = wordParserService.extractText(answersFile);

        String rawQuestionsResponse = aiService.extractQuestionsFromText(examText);
        String structuredQuestionsJson = extractJsonContent(rawQuestionsResponse);
        List<Map<String, Object>> questions = objectMapper.readValue(structuredQuestionsJson, new TypeReference<>() {});

        Map<Integer, String> studentAnswers = parseStudentAnswers(answersText);

        List<Map<String, Object>> analysisDataList = new ArrayList<>();
        Map<String, List<Boolean>> topicCorrectness = new HashMap<>();

        for (Map<String, Object> question : questions) {
            int id = (Integer) question.get("id");
            String correctAnswer = (String) question.get("answer");
            String topic = (String) question.getOrDefault("topic", "常规");
            String studentAnswer = studentAnswers.getOrDefault(id, "");
            boolean isCorrect = correctAnswer.equalsIgnoreCase(studentAnswer);
            topicCorrectness.computeIfAbsent(topic, k -> new ArrayList<>()).add(isCorrect);
            Map<String, Object> analysisEntry = new HashMap<>(question);
            analysisEntry.put("studentAnswer", studentAnswer);
            analysisEntry.put("isCorrect", isCorrect);
            analysisDataList.add(analysisEntry);
        }

        List<GradingReportDto.TopicAccuracy> accuracyByTopic = new ArrayList<>();
        for (Map.Entry<String, List<Boolean>> entry : topicCorrectness.entrySet()) {
            String topic = entry.getKey();
            List<Boolean> results = entry.getValue();
            long correctCount = results.stream().filter(Boolean::booleanValue).count();
            double accuracy = (double) correctCount / results.size();
            accuracyByTopic.add(new GradingReportDto.TopicAccuracy(topic, accuracy));
        }

        // --- 【核心改动】在这里，我们将AI返回的定性分析JSON解析为一个通用的Map ---
        String rawReportResponse = aiService.generateAnalysisReport(objectMapper.writeValueAsString(analysisDataList));
        String qualitativeReportJson = extractJsonContent(rawReportResponse);

        // 将AI返回的JSON解析为一个更灵活的Map，而不是直接映射到DTO
        Map<String, Object> qualitativeData = objectMapper.readValue(qualitativeReportJson, new TypeReference<Map<String, Object>>() {});

        // --- 组装最终的DTO ---
        GradingReportDto finalReport = new GradingReportDto();
        finalReport.setAccuracyByTopic(accuracyByTopic);

        // 从Map中安全地获取数据，如果某个字段不存在，则返回一个空列表，避免前端报错
        finalReport.setStrengths((List<String>) qualitativeData.getOrDefault("strengths", Collections.emptyList()));
        finalReport.setWeaknesses((List<String>) qualitativeData.getOrDefault("weaknesses", Collections.emptyList()));
        finalReport.setSuggestions((List<String>) qualitativeData.getOrDefault("suggestions", Collections.emptyList()));

        long totalCorrect = topicCorrectness.values().stream().flatMap(List::stream).filter(Boolean::booleanValue).count();
        int totalQuestions = questions.size();
        finalReport.setCorrectCount((int) totalCorrect);
        finalReport.setTotalCount(totalQuestions);
        finalReport.setOverallScore(totalQuestions > 0 ? (double) totalCorrect / totalQuestions * 100 : 0);

        return finalReport;
    }
    /**
     * 【已重写】
     * 新的解析逻辑，可以处理不带题号的答案列表。
     * 它会简单地按行读取，第一行视为第1题答案，第二行视为第2题，以此类推。
     */
    private Map<Integer, String> parseStudentAnswers(String text) {
        Map<Integer, String> answers = new HashMap<>();
        String[] lines = text.split("\\r?\\n");
        int questionId = 1; // 题号从1开始计数
        for (String line : lines) {
            String trimmedLine = line.trim();
            if (!trimmedLine.isEmpty()) { // 忽略空行
                answers.put(questionId, trimmedLine);
                questionId++; // 每处理一行，题号加1
            }
        }
        return answers;
    }

    private String extractJsonContent(String rawResponse) {
        // ... 此辅助方法逻辑完全不变 ...
        try {
            JsonNode rootNode = objectMapper.readTree(rawResponse);
            JsonNode textNode = rootNode.path("candidates").path(0).path("content").path("parts").path(0).path("text");
            if (!textNode.isMissingNode()) {
                return extractJsonContent(textNode.asText());
            }
        } catch (Exception e) {
            // ...
        }
        String trimmedResponse = rawResponse.trim();
        if (trimmedResponse.startsWith("```json")) {
            return trimmedResponse.substring(7, trimmedResponse.lastIndexOf("```")).trim();
        }
        if (trimmedResponse.startsWith("```")) {
            return trimmedResponse.substring(3, trimmedResponse.length() - 3).trim();
        }
        int startIndex = Math.max(rawResponse.indexOf('{'), rawResponse.indexOf('['));
        int endIndex = Math.min(rawResponse.lastIndexOf('}'), rawResponse.lastIndexOf(']'));
        if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) {
            return rawResponse.substring(startIndex, endIndex + 1);
        }
        return rawResponse;
    }
}